﻿#include "player_object.h"


void StateMachine::update(PlayerState state)
{
    frameCounter++;

    if (state == PlayerState::WalkingLeft)
    {
        if (!(currentState == PlayerState::WalkingLeft))
        {
            currentState = state;
            frameCounter = 0;
        }
        else if (frameCounter >= 12)
        {
            walkFrame = (walkFrame + 1) % 2;
            frameCounter = 0;
        }
    }
    else if (state == PlayerState::WalkingRight)
    {
        if (!(currentState == PlayerState::WalkingRight))
        {
            currentState = state;
            frameCounter = 0;
        }
        else if (frameCounter >= 12)
        {
            walkFrame = (walkFrame + 1) % 2;
            frameCounter = 0;
        }
    }
    else
    {
        currentState = PlayerState::Standing;
        walkFrame = 0;
    }

    switch (currentState)
    {
    case PlayerState::Standing:
        currentTextureIndex = (size_t)ObjectTexture::Standing;
        break;
    case PlayerState::WalkingLeft:
        currentTextureIndex = (size_t)ObjectTexture::WalkLeft1 + walkFrame;
        break;
    case PlayerState::WalkingRight:
        currentTextureIndex = (size_t)ObjectTexture::WalkRight1 + walkFrame;
        break;
    default:
        currentTextureIndex = (size_t)ObjectTexture::Standing;
        break;
    }
}

size_t StateMachine::getCurrentTextureIndex() const { return currentTextureIndex; }


PlayerObject::PlayerObject(int x, int y, int width, int height, std::vector<SDL_Texture*>& textures, KeyMap keyMap)
    : textures(textures), keyMap(keyMap), GameObject(x, y, width, height, false) {}

void PlayerObject::render(SDL_Renderer* renderer)
{
    SDL_FRect rect = { realX, realY, static_cast<float>(width), static_cast<float>(height) };
    SDL_RenderTexture(renderer, textures[stateMachine.getCurrentTextureIndex()], nullptr, &rect);
}

void PlayerObject::handleInput(const bool* keystates)
{
    velocityX = 0;
    PlayerState state = PlayerState::Standing;
    if (keystates[keyMap.key_left])
    {
        velocityX = -MOVE_SPEED;
        state = PlayerState::WalkingLeft;
    }
    if (keystates[keyMap.key_right])
    {
        velocityX = MOVE_SPEED;
        state = PlayerState::WalkingRight;
    }
    if (keystates[keyMap.key_jump])
    {
        jump();
    }
    stateMachine.update(state);
}